using System;
using Newtonsoft.Json;

namespace ERP_SaaS_WinForm.生产工单_报工_工序.Process
{
    /// <summary>
    /// Safely parses DateTime? from JSON, accepting null, empty string, or invalid formats.
    /// Returns null when the value cannot be parsed.
    /// </summary>
    public sealed class NullableDateTimeConverter : JsonConverter<DateTime?>
    {
        public override DateTime? ReadJson(JsonReader reader, Type objectType, DateTime? existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) return null;
            if (reader.TokenType == JsonToken.Date)
            {
                if (reader.Value is DateTime dt) return dt;
                return null;
            }
            if (reader.TokenType == JsonToken.String)
            {
                var s = (reader.Value as string)?.Trim();
                if (string.IsNullOrEmpty(s) || string.Equals(s, "null", StringComparison.OrdinalIgnoreCase)) return null;
                if (DateTime.TryParse(s, out var dt)) return dt;
                return null;
            }
            return null;
        }

        public override void WriteJson(JsonWriter writer, DateTime? value, JsonSerializer serializer)
        {
            if (value.HasValue)
            {
                // ISO 8601 format with seconds to be consistent with most backends
                writer.WriteValue(value.Value.ToString("yyyy-MM-ddTHH:mm:ss"));
            }
            else
            {
                writer.WriteNull();
            }
        }
    }

    /// <summary>
    /// Safely parses non-nullable DateTime; if input is null/invalid, returns DateTime.MinValue.
    /// </summary>
    public sealed class SafeDateTimeConverter : JsonConverter<DateTime>
    {
        public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) return DateTime.MinValue;
            if (reader.TokenType == JsonToken.Date && reader.Value is DateTime dt) return dt;
            if (reader.TokenType == JsonToken.String)
            {
                var s = (reader.Value as string)?.Trim();
                if (string.IsNullOrEmpty(s) || string.Equals(s, "null", StringComparison.OrdinalIgnoreCase)) return DateTime.MinValue;
                if (DateTime.TryParse(s, out var parsed)) return parsed;
                return DateTime.MinValue;
            }
            return DateTime.MinValue;
        }

        public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
        {
            writer.WriteValue(value.ToString("yyyy-MM-ddTHH:mm:ss"));
        }
    }
}



